package ru.aslanov.schedule.utils;

import ru.aslanov.schedule.server.PMF;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import java.io.Serializable;
import java.util.Collections;
import java.util.logging.Logger;

/**
 * @author Sergey Aslanov
 *         Created: 1/28/11 3:26 PM
 */
public class MemCacheUtil {
    private static final Logger log = Logger.getLogger(MemCacheUtil.class.getName());
    static Cache cache;

    static {
        try {
            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
            cache = cacheFactory.createCache(Collections.emptyMap());
        } catch (CacheException e) {
            throw new RuntimeException("Cannot create cache", e);
        }
    }


    public static Object getAndCacheEntity(Class entityClass, String encodedKey) {
        Object obj = cache.get(encodedKey);
        if (obj == null) {
            log.fine("Loading entity " + entityClass.getSimpleName() + " from DB: " + encodedKey);
            final PersistenceManager pm = PMF.getThreadLocalPersistenceManager();
            obj = pm.getObjectById(entityClass, encodedKey);
            pm.retrieve(obj);
            pm.makeTransient(obj);
            cache.put(encodedKey, obj);
        } else {
            //log.fine("Using cached entity " + entityClass.getSimpleName());
        }
        return obj;
    }


    public static void cacheObject(String cacheKey, Serializable object) {
        log.fine("Caching object " + object.getClass().getSimpleName() + " with key " + cacheKey);
        cache.put(cacheKey, object);
    }
    public static void removeObjectFromCache(String cacheKey) {
        log.fine("Removing object from cache: " + cacheKey);
        cache.remove(cacheKey);
    }
    public static Object getObjectFromCache(String cacheKey) {
        return cache.get(cacheKey);
    }

    public static void removeEntityFromCache(String encodedKey) {
        log.fine("Removing cached entity: " + encodedKey);
        cache.remove(encodedKey);
    }

    public static void clearCache() {
        log.info("Clearing cache");
        cache.clear();
    }
}
